<template>
  <div class="group-chat-module">
    <div class="group-chat-header">
      <font-awesome-icon :icon="['fas', 'people-group']"/>
      群聊: {{ room.name }}
    </div>
    <div class="group-chat-list">
      <ParticipantWindow :ref="`participant_${participant.id}`" v-for="participant in participants"
                         :key="participant.id" :participant="participant" :room="room" :roomId="roomId" :self="self"
                         :participantCastFullScreen="participantCastFullScreen"
                         :participantCancelFullScreen="participantCancelFullScreen"
                         :kick="kick"/>
    </div>
    <div class="group-chat-bottom">
      <div class="user-clear" v-if="self?.id === room.ownerId">
        <font-awesome-icon class="user-clear-icon" @click="kickAllParticipants" :style="{color:'#B91C1C'}" :icon="['fas', 'users-slash']"/>
      </div>
      <div class="group-chat-exit">
        <font-awesome-icon class="group-chat-exit-icon" @click="exitRoom" :style="{color:'#d6e3e3'}" :icon="['fas', 'right-from-bracket']"/>
      </div>
    </div>
  </div>
</template>

<script>
import ParticipantWindow from "@/components/right/ParticipantWindow.vue";
import {
  reportGroupChatParticipantEnter,
  reportGroupChatParticipantExit,
  reportGroupChatParticipantForceKick,
  reportGroupChatParticipantWelcome,
  subGroupChatParticipantEnter,
  subGroupChatParticipantExit,
  subGroupChatParticipantForceKick,
  subGroupChatParticipantWelcome,
  subRoomDismiss,
  unSubGroupChatParticipantEnter,
  unSubGroupChatParticipantExit,
  unSubGroupChatParticipantForceKick,
  unSubGroupChatParticipantWelcome,
  unSubRoomDismiss,
} from "@/api/nats/group_chat";

export default {
  name: "GroupChat",
  components: {
    ParticipantWindow
  },
  inject: ['localStream'],
  props: {
    groupCallSession: {
      type: Object
    },
    user: {
      type: Object
    },
    exitGroupChat: {
      type: Function
    },
    participantCastFullScreen:{
      type: Function
    },
    participantCancelFullScreen: {
      type: Function
    }
  },
  data() {
    return {
      room: {},
      roomId: null,
      self: null,
      participants: [],
      groupChatCommand:{
        enter:"enter",
        exit:"exit",
        kick:"kick",
        kicked: "kicked",
        welcome:"welcome",
        dismiss:"dismiss",
      }
    }
  },
  methods: {
    kickAllParticipants() {
      this.participants.forEach(participant => {
        this.kick(participant);
      })
    },
    kick(participant) {
      reportGroupChatParticipantForceKick(this.roomId, this.self.id, participant.id, {
        type: this.groupChatCommand.kick,
        roomId: this.roomId,
        kicker: this.self,
        kicked: participant
      })
      this.participants = this.participants.filter(item => item.id !== participant.id);
    },
    init() {
      let {callId, room} = this.groupCallSession;
      this.roomId = callId
      this.room = room;
      this.self = this.user;
      this.$message.success(`进入房间:${this.room.name}`)
      this.subscribe();
      // 发布进入房间
      reportGroupChatParticipantEnter(this.roomId, this.self.id, {
        type: this.groupChatCommand.enter,
        roomId: this.roomId,
        participant: this.self,
      })
    },
    subscribe() {
      subGroupChatParticipantForceKick(this.roomId, this.self.id, this.receivedParticipantForcedKick)
      subGroupChatParticipantEnter(this.roomId, this.receivedParticipantEnterRoom)
      subGroupChatParticipantWelcome(this.roomId, this.self.id, this.receivedParticipantWelcome)
      subGroupChatParticipantExit(this.roomId, this.receivedParticipantExit)
      subRoomDismiss(this.roomId, this.receivedRoomDismiss)
    },
    receivedParticipantEnterRoom(data) {
      let {participant} = data;
      // 如果是自己,则不处理
      if (participant.id === this.self.id) {
        return;
      }
      this.participants.push(participant);
      this.$message.info(`${participant.nickname}进入房间`);
      // 发布欢迎
      this.$nextTick(() => {
        reportGroupChatParticipantWelcome(this.roomId, this.self.id, participant.id, {
          type: this.groupChatCommand.welcome,
          roomId: this.roomId,
          participant: this.self,
        })
      })
    },
    receivedParticipantWelcome(data) {
      let {participant} = data;
      this.participants.push(participant);
      // 发送offer
      this.$nextTick(() => {
        this.$refs[`participant_${participant.id}`][0].sendOffer()
      })
    },
    receivedParticipantForcedKick() {
      this.$message.error(`你被踢出房间`);
      this.participants = [];
      reportGroupChatParticipantExit(this.roomId, this.self.id, {
        type: this.groupChatCommand.kicked,
        roomId: this.roomId,
        participant: this.self,
      });
      this.participants = [];
      this.exitGroupChat();
    },
    receivedParticipantExit(data) {
      let {participant , type} = data;
      // 如果是自己,则不处理
      if (participant.id === this.self.id) {
        return;
      }
      this.participantCancelFullScreen(participant.id)
      if (type === this.groupChatCommand.kicked) {
        this.$message.warning(`${participant.nickname}被踢出房间`);
      } else {
        this.$message.info(`${participant.nickname}退出房间`);
      }
      this.participants = this.participants.filter(item => item.id !== participant.id);
    },
    receivedRoomDismiss() {
      this.$message.error(`当前房间被解散`);
      this.participants = [];
      this.exitGroupChat();
    },
    exitRoom() {
      reportGroupChatParticipantExit(this.roomId, this.self.id, {
        type: this.groupChatCommand.exit,
        roomId: this.roomId,
        participant: this.self,
      });
      this.participants = [];
      this.exitGroupChat();
    },
    resetOtherParticipantFullScreen(participantId){
      this.participants.forEach(participant => {
        if (participant.id !== participantId){
          this.$refs[`participant_${participant.id}`][0].resetFullScreen();
        }
      })
    },
    resetSpecifyParticipantFullScreen(participantId){
       let participantRef = this.$refs[`participant_${participantId}`][0]
       if (participantRef){
          participantRef.resetFullScreen();
       }
    },
    unsubscribe() {
      unSubGroupChatParticipantEnter(this.roomId)
      unSubGroupChatParticipantForceKick(this.roomId, this.self.id)
      unSubGroupChatParticipantWelcome(this.roomId, this.self.id)
      unSubGroupChatParticipantExit(this.roomId)
      unSubRoomDismiss(this.roomId)
    }
  },
  mounted() {
    this.init();
  },
  beforeDestroy() {
    this.unsubscribe();
  }
}
</script>


<style scoped>
.group-chat-module {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1.2rem 0.6rem;
  gap: 0.3rem;
  min-height: 0;
  overflow: hidden;
  box-sizing: border-box;
}

.group-chat-header {
  display: flex;
  align-items: center;
  gap: 0.5vw;
  font-size: 1.1rem;
  font-weight: bold;
  color: #fff;
  margin-bottom: 0.5rem;
}

.group-chat-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  min-height: 200px;
  overflow-y: auto;
  /* 添加内边距补偿，避免内容紧贴滚动条 */
  padding-right: 8px;
  flex: 1 1;
}

.group-chat-bottom {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  gap: 0.5vw;
  color: #fff;
  width: 100%;
  height: 4%;
}

.group-chat-bottom div {
  width: 50%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.group-chat-exit-icon:hover, .user-clear-icon:hover {
  cursor: pointer;
  opacity: 0.9;
  transform: scale(1.1);
}

</style>